import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [
  // 设置一级路由
  {
    path: "/login",
    component: () => import("@/views/Login"),
  },
  {
    path: "/admin",
    name: "home",
    component: () => import("@/views/Home"),
    redirect: { name: "dashboard" },
    // 二级路由
    children: [
      {
        path: "dashboard",
        name: "dashboard",
        component: () => import("@/views/Home/Dashboard"),
      },
      { path: "category", component: () => import("@/views/Home/Category") },
      { path: "article", component: () => import("@/views/Home/Article") },
      { path: "user", component: () => import("@/views/Home/User") },
      { path: "comments", component: () => import("@/views/Home/Comments") },
    ],
  },
  {
    path: "/",
    component: () => import("@/views/Home"),
  },
  {
    path: "*",
    component: () => import("@/views/NotFound"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 设置全局前置导航守卫
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem("token");
  if (token) {
    // 已登录
    if (to.path == "/login") {
      next("/admin");
    } else {
      next();
    }
  } else {
    // 未登录
    if (to.path == "/login") {
      next();
    } else {
      Vue.prototype.$message({
        type: "error",
        message: "请先登录",
        duration: 2000,
      });
      next("/login");
    }
  }
});
export default router;
